﻿using AbstractMq;
using JT809.Protocol;
using JT809.Protocol.Configs;
using JT809.Protocol.Enums;
using JT809.Protocol.Extensions;
using JT809.Protocol.MessageBody;
using JT809.Protocol.Metadata;
using JT809.Protocol.SubMessageBody;
using JTT809_2011_Service.Extensions;
using JTT809_2011_Service.JT809;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace JTT809_2011_Service
{
    public class JT809InferiorService : IHostedService
    {
        private readonly JT809Serializer _JT809Serializer;
        private readonly JT809MainClient _mainClient;
        private readonly ILogger<JT809InferiorService> _logger;
        private readonly JT809HeaderOptions _JT809HeaderOptions;
        private readonly ISubscriber _ISubscriber;
        private readonly IMessageSerializer _IMessageSerializer;
        private readonly IPublisher _IPublisher;
        private readonly JT809_0x1001Options _JT809_0x1001Options;

        #region ctor
        public JT809InferiorService
            (
              IJT809Config jT809Config,
              JT809HeaderOptions jT809HeaderOptions,
              ILoggerFactory loggerFactory,
              JT809MainClient mainClient,
              ISubscriber subscriber,
              IMessageSerializer messageSerializer,
              IPublisher publisher,
              JT809_0x1001Options jT809_0x1001Options
            )
        {
            _JT809Serializer = jT809Config.GetSerializer();
            _JT809HeaderOptions = jT809HeaderOptions;
            _mainClient = mainClient;
            _logger = loggerFactory.CreateLogger<JT809InferiorService>();
            _ISubscriber = subscriber;
            _IMessageSerializer = messageSerializer;
            _IPublisher = publisher;
            _JT809_0x1001Options = jT809_0x1001Options;
        }
        #endregion
        public Task StartAsync(CancellationToken cancellationToken)
        {
            var connect = _mainClient.Login(new JT809_0x1001
            {
                DownLinkIP = _JT809_0x1001Options.DownLinkIP,
                DownLinkPort = _JT809_0x1001Options.DownLinkPort,
                UserId = _JT809_0x1001Options.UserId,
                Password = _JT809_0x1001Options.Password
            }).Result;
            if (connect)
            {
                //_IPublisher.Publish<SchoolBusModel>("SchoolBusExchange", "SchoolBusQueue_Publish", "SchoolBus", new SchoolBusModel
                //{
                //    VehicleNo = "粤A12345",
                //    Day = (byte)(DateTime.Now.Day),
                //    Month = (byte)(DateTime.Now.Month),
                //    Year = (ushort)(DateTime.Now.Year),
                //    Hour = (byte)(DateTime.Now.Hour),
                //    Minute = (byte)(DateTime.Now.Minute),
                //    Second = (byte)(DateTime.Now.Second),
                //    Alarm = 0,
                //    Direction = 2,
                //    State = JT808_Status.定位.ToUInt32Value(),
                //    Altitude = 32,
                //    Lat = 122334565,
                //    Lon = 12354563,
                //    Vec1 = 112,
                //    Vec2 = 22,
                //    Vec3 = 12

                //});
                Console.WriteLine("成功了");
                _ISubscriber.Subscribe("SchoolBus.ExchangeName", "SchoolBus.QueueName", "SchoolBus.QueueName", e =>
                {
                    bool successed = false;
                    var result = _IMessageSerializer.DeserializeBytes<SchoolBusModel>(e);
                    JT809_0x1200 jT809_0X1200 = new JT809_0x1200();
                    jT809_0X1200.VehicleColor = JT809VehicleColorType.其他;
                    jT809_0X1200.VehicleNo = result.VehicleNo;
                    jT809_0X1200.SubBusinessType = JT809SubBusinessType.实时上传车辆定位信息.ToUInt16Value();
                    jT809_0X1200.SubBodies = new JT809_0x1200_0x1202()
                    {
                        VehiclePosition = new JT809VehiclePositionProperties
                        {
                            Day = result.Day,
                            Month = result.Month,
                            Year = result.Year,
                            Hour = result.Hour,
                            Minute = result.Minute,
                            Second = result.Second,
                            Alarm = result.Alarm,
                            Direction = result.Direction,
                            State = result.State,
                            Altitude = result.Altitude,
                            Lat = result.Lat,
                            Lon = result.Lon,
                            Vec1 = result.Vec1,
                            Vec2 = result.Vec2,
                            Vec3 = result.Vec3
                        }
                    };
                    var package = JT809BusinessType.主链路车辆动态信息交换业务.Create(jT809_0X1200);
                    package.Header.MsgGNSSCENTERID = _JT809HeaderOptions.MsgGNSSCENTERID;
                    package.Header.Version = _JT809HeaderOptions.Version;
                    package.Header.EncryptKey = _JT809HeaderOptions.EncryptKey;
                    package.Header.EncryptFlag = _JT809HeaderOptions.EncryptFlag;
                    //_logger.LogDebug(_JT809Serializer.Serialize(package).ToHexString());
                    if (_mainClient.SendAsync(new JT809Response(package, 1024)).Result)
                    {
                        successed = true;
                    }
                    return successed;
                });



                //while (true)
                //{
                //    Task.Run(() =>
                //    {
                //        Thread.Sleep(6 * 1000);
                //        JT809_0x1200 jT809_0X1200 = new JT809_0x1200();
                //        jT809_0X1200.VehicleColor = JT809VehicleColorType.黄色;
                //        jT809_0X1200.VehicleNo = "粤A12345";
                //        jT809_0X1200.SubBusinessType = JT809SubBusinessType.实时上传车辆定位信息.ToUInt16Value();
                //        jT809_0X1200.SubBodies = new JT809_0x1200_0x1202()
                //        {
                //            VehiclePosition = new JT809VehiclePositionProperties
                //            {
                //                Day = (byte)(DateTime.Now.Day),
                //                Month = (byte)(DateTime.Now.Month),
                //                Year = (ushort)(DateTime.Now.Year),
                //                Hour = (byte)(DateTime.Now.Hour),
                //                Minute = (byte)(DateTime.Now.Minute),
                //                Second = (byte)(DateTime.Now.Second),
                //                Alarm = JT808_Alarm.当天累计驾驶超时.ToUInt32Value(),
                //                Direction = 2,
                //                State = JT808_Status.满载.ToUInt32Value(),
                //                Altitude = 32,
                //                Lat = 122334565,
                //                Lon = 12354563,
                //                Vec1 = 112,
                //                Vec2 = 22,
                //                Vec3 = 12
                //            }
                //        };
                //        var package = JT809BusinessType.主链路车辆动态信息交换业务.Create(jT809_0X1200);
                //        package.Header.MsgGNSSCENTERID = _JT809HeaderOptions.MsgGNSSCENTERID;
                //        package.Header.Version = _JT809HeaderOptions.Version;
                //        package.Header.EncryptKey = _JT809HeaderOptions.EncryptKey;
                //        package.Header.EncryptFlag = _JT809HeaderOptions.EncryptFlag;
                //        _logger.LogDebug(_JT809Serializer.Serialize(package).ToHexString());
                //        _mainClient.SendAsync(new JT809Response(package, 1024));
                //        _logger.LogDebug($"Thread:{Thread.CurrentThread.ManagedThreadId}-2s");
                //    });
                //}
                //});
            }
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
}
